package cn.qiyu5522.tk_ems.controller.admin;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.qiyu5522.tk_ems.entity.Student;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.dto.StudentExcelDTO;
import cn.qiyu5522.tk_ems.entity.validateGroup.UpdateElement;
import cn.qiyu5522.tk_ems.entity.vo.StudentVO;
import cn.qiyu5522.tk_ems.exception.BusinessException;
import cn.qiyu5522.tk_ems.myanotation.WebLog;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.result.ResponseEnum;
import cn.qiyu5522.tk_ems.service.StudentService;
import cn.qiyu5522.tk_ems.utils.EasyExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tonkey
 * @since 2023-01-26
 */
@Api(tags = "学生模块")
@RestController
@RequestMapping("/admin/student")
public class StudentController {
    @Resource
    private StudentService studentService;

    // 增
    @ApiOperation("学生新增--批量")
    @ApiImplicitParam(name = "studentList", value = "学生信息集合", required = true, dataTypeClass = List.class)
    @PostMapping("/add")
    public R addStudent(@Valid @RequestBody List<StudentVO> studentList) {
        int effect = studentService.saveMore(studentList);
        return effect > 0 ? R.ok().message("添加成功") : R.error().message("添加失败");
    }

    // 删
    @ApiOperation("学生信息删除--批量")
    @ApiImplicitParam(name = "ids", value = "学号集合", required = true, dataTypeClass = List.class)
    @PostMapping("/remove")
    public R removeStudent(@RequestBody List<Long> ids) {
        boolean save = studentService.removeByIds(ids);
        return save ? R.ok().message("删除成功") : R.error().message("删除失败");
    }

    // 改
    @ApiOperation("学生信息编辑")
    @ApiImplicitParam(name = "student", value = "学生对象", required = true, dataTypeClass = Student.class)
    @PutMapping("/edit")
    public R editStudent(@Validated(UpdateElement.class) @RequestBody Student student) {
        boolean b = studentService.updateById(student);
        return b ? R.ok().message("编辑成功") : R.error().message("编辑失败");
    }

    // 查
//    @SaCheckPermission(value = "user.view")
    @WebLog(description = "学生信息查询--分页条件查询")
    @ApiOperation("学生信息查询--分页条件查询")
    @ApiImplicitParam(name = "queryParamDTO", value = "查询条件封装对象", required = true, defaultValue = "{}", dataTypeClass = QueryParamDTO.class)
    @PostMapping("/query")
    public R query(@Valid @RequestBody QueryParamDTO<StudentVO> queryParamDTO) {
        return studentService.queryStudentByPageCondition(queryParamDTO);
    }

    // 获取院系专业树结构
    @WebLog(description = "获取院系专业班级树结构")
    @ApiOperation("获取院系专业树班级结构")
    @GetMapping("/queryDepAndMaJorAndClassroom")
    public R queryDepAndMaJorAndClassroom() {
        return studentService.getDepAndMaJorAndClassroom();
    }

    // 学生信息的导出
    @ApiOperation("学生信息导出")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(value = "导出数据的id", name = "ids", required = false, dataTypeClass = Array.class),
                    @ApiImplicitParam(value = "文件名称", name = "fileName", required = false, dataTypeClass = String.class)
            }
    )
    @GetMapping("/exportStudentData")
//    @SaIgnore
    public R exportStudentData(
            @RequestParam(value = "ids", required = false) Long[] ids,
            @RequestParam(value = "fileName", required = false) String fileName,
            @RequestParam("token") String token,
            HttpServletResponse response) {

        //调工具类中的方法
        try {
//            String fileName = "studentList";
            List<StudentExcelDTO> studentDTOS = studentService.queryStudentListByIds(ids);
            EasyExcelUtils.resposeEasyExcel(response, fileName, studentDTOS);
            return R.ok();
        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
        }
    }

    // 学生信息的导入
    @ApiOperation("学生信息导入")
    @ApiImplicitParam(name = "file", value = "上传的文件对象", required = true, dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    @PostMapping("/importStudentData")
    @SaIgnore
    public R importStudentData(@RequestParam(required = false, name = "file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (!(suffixName.equals(".xlsx"))) {
            System.out.println("请上传xlsx格式文件");
        }
        // 获取Excel 表中的数据
        List<StudentExcelDTO> listByFile = EasyExcelUtils.getListByFile(file, StudentExcelDTO.class);
        // 带插入的数据
        R result = studentService.handleMapConvertAndSave(listByFile);
        return result;
    }

    // 学生信息的模板
    @ApiOperation("学生信息导入模板")
    @ApiImplicitParam(value = "token", name = "token", required = false, dataType = "String",dataTypeClass = String.class)
    @GetMapping("/importStudentDataTemplate")
    public R importStudentDataTemplate(
                                       @RequestParam("token") String token,
                                       HttpServletResponse response){
        //调工具类中的方法
        try {
            String fileName = "studentDataTemplate";
            List<StudentExcelDTO> studentDTOS = new ArrayList<>();
            StudentExcelDTO studentExcelDTO = new StudentExcelDTO();
            studentExcelDTO.setId(23321752417L);
            studentExcelDTO.setName("王小虎");
            studentExcelDTO.setAge(18);
            studentExcelDTO.setGender(1);
            studentExcelDTO.setClassroom("计科一班");
            studentExcelDTO.setMajor("计算机科学与技术");
            studentExcelDTO.setDepartment("计算机信息与科学学院");
            studentExcelDTO.setPhone("132XXXXXXXX");
            studentExcelDTO.setCreateTime(LocalDateTime.now());
            studentExcelDTO.setUpdateTime(LocalDateTime.now());
            studentDTOS.add(studentExcelDTO);
            EasyExcelUtils.resposeEasyExcel(response, fileName, studentDTOS);
            return R.ok();
        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            throw new BusinessException(ResponseEnum.EXPORT_DATA_ERROR, e);
        }
    }

    @ApiOperation(value = "查询学号是否存在")
    @ApiImplicitParam(name = "studentId",value = "学号",dataType = "Long")
    @GetMapping("/checkStudentIdIsExisting/{studentId}")
    public R checkStudentIdIsExisting(@PathVariable Long studentId){
        return studentService.checkStudentIdIsExisting(studentId);
    }

    @ApiOperation(value = "根据学号查询学生信息")
    @ApiImplicitParam(name = "studentId",value = "学号",dataType = "Long")
    @GetMapping("/getStudentInfoById/{studentId}")
    public R getStudentInfoById(@PathVariable Long studentId){
        return studentService.getStudentInfoById(studentId);
    }





}
